<?

$id = -1;
$msg = "";
$title = "";
$error = "";
if(isset($_POST['kurs_id']) && isset($_POST['title']) && isset($_POST['msg'])){
$id = $_POST['kurs_id'];
$msg = $_POST['msg'];
$title = $_POST['title'];

if(!(is_numeric($id) && $id > 0 && $title != "" && $msg != "")){
	$error .= "Empfangene Daten sind ungueltig<br>";
}
}
else{
	if(isset($_GET['pid'])){
		$pid = (int) ($_GET['pid']);	
		$query = "SELECT name FROM `2011_veranstaltung` WHERE id = '$pid'";	
		$result = doQuery($query);
		$array = mysql_fetch_row($result);
		$kurs_title = $array[0];
		if(strlen($kurs_title) > 28) $kurs_title = substr($kurs_title,0,28)."...";
		echo "<form action='?id=rundmail' method='POST'>";
		echo "<input type='hidden' style='width:500px' name='kurs_id' value='".$pid."'><br>";
		echo "<input type='text' style='width:500px' name='title' value='"."Sommeruni ".$kurs_title.""."'><br>";
		echo "<textarea name='msg' style=\"width:500px;height:150px;\">Hallo liebe Teilnehmer,\n</textarea><br>";
		echo "<input type=\"submit\" name=\"schickeEmail\" class=\"button\" value=\"Rundmail verschicken\"/>";
		echo "</form><br><br><br>";
	return;
	}
	else{
	$error .= "Fehlerhafter Aufruf der Seite<br>";	
	}
}

//first stop of programm if error is != ""
if($error != ""){
	echo $error;
	return;
}

//query database, get ALL email adresses of given course id
$emails = array();
$query = "SELECT 2011_schueler.email FROM `2011_hoert`,2011_schueler WHERE 2011_hoert.ver_id = $id AND 2011_hoert.sch_id = 2011_schueler.id";
$result = doQuery($query);
$array = mysql_fetch_row($result);
for($i = 0; $array != false; $i++){
 $emails[$i] = $array[0];
 $array = mysql_fetch_row($result);
}


//prepare and send email !!
echo "<div style='background-color:#EFE;padding:5px'>DEBUG alle Emailadressen: <br>";
foreach($emails as $email){
	echo $email ."<br>";
	send_email($email,$title,$msg);	
}
echo "</div>";

$anz = count($emails);
echo "Es wurden erfolgreich $anz Emails an alle Teilnehmer des Kurses mit ID $id verschickt.";
//but hacker still needs to know password
echo "<h5>Folgende Email wurde gesendet</h5>";
echo "<div style='background-color:#EFE;padding:5px'>$title</div>";
//replace \n with <br> for displanign email correctly
echo "<div style='background-color:#EEE;padding:5px'>";
echo nl2br($msg);
echo "</div>";


?>